package org.inspiration.dudu.web.service.content.imp;

import lombok.RequiredArgsConstructor;
import org.inspiration.dudu.common.util.FileUtil;
import org.inspiration.dudu.content.model.dto.QuestionDTO;
import org.inspiration.dudu.content.model.entity.QuestionEntity;
import org.inspiration.dudu.content.model.vo.QuestionSimpleVO;
import org.inspiration.dudu.content.model.vo.QuestionVO;
import org.inspiration.dudu.content.service.QuestionService;
import org.inspiration.dudu.user.service.UserService;
import org.inspiration.dudu.web.service.content.QuestionFacadeService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

/**
 * QuestionFacadeServiceImpl类实现了与问题相关的操作。
 */
@Service
@RequiredArgsConstructor
public class QuestionFacadeServiceImpl implements QuestionFacadeService {

    @Value("${dudu.file.upload-path}")
    private String uploadPath; // 文件上传路径

    private final FileUtil fileUtil; // 文件工具类
    private final QuestionService questionService; // 问题服务
    private final UserService userService; // 用户服务

    /**
     * 上传问题
     * 
     * @param questionDTO 要上传的问题数据传输对象
     * @return 生成的唯一标识符
     */
    @Override
    @Transactional
    public String uploadQuestion(QuestionDTO questionDTO) {
        String uuid = UUID.randomUUID().toString(); // 生成唯一标识符
        String filename = uuid + ".html"; // 生成文件名
        Path subPath = Paths.get("questions", filename); // 问题文件的相对路径
        // 将内容存入文件
        fileUtil.upload(questionDTO.getContent(), subPath);
        // 将问题实体存入数据库
        String contentFilePath = Paths.get(uploadPath).resolve(subPath).toString();
        QuestionEntity questionEntity = questionService.transToEntity(questionDTO, contentFilePath, uuid);
        questionService.createQuestion(questionEntity);
        // 增加发布者的发布问题的数量
        userService.increaseQuestionCount(questionDTO.getUserId());
        return uuid; // 返回问题的唯一标识符
    }

    /**
     * 根据问题ID获取问题信息
     * 
     * @param id 问题的唯一标识符
     * @return 对应问题的值对象
     */
    @Override
    public QuestionVO getQuestionById(String id) {
        return questionService.getQuestionById(id);
    }

    @Override
    public List<QuestionVO> getQuestionOrderByDESC(Integer pageNum, Integer pageSize) {
        return questionService.getQuestionsOrderByDESC(pageNum, pageSize);
    }

    @Override
    public List<QuestionVO> getQuestionsByUserIdOrderByDESC(Long userId, Integer pageNum, Integer pageSize) {
        return questionService.getQuestionsByUserIdOrderByDESC(userId, pageNum, pageSize);
    }
}
